<?php

class ProductController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	//public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return $this->getRules();
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView()
	{
		print_r('<pre>');
            print_r($this->getRules());
            print_r('</pre>');
            exit();
	}

	
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new ProductModel('search');
		$model->unsetAttributes();  // clear any default values
		$model->title = 'Game';
                //$model->attributes=$_GET['ProductModel'];
                    
                    print_r('<pre>');
                    print_r($model->attributes);
                    print_r('</pre>');
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return ProductModel the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=ProductModel::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param ProductModel $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='post-model-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        
        public function actionIndex(){
            //init page value
            $pagevals = array(
                'page_title' => "Quản trị sản phẩm",
                'subpage_title' => 'Danh sách sản phẩm',
                //'action' => 'product/abc'
            );
            
            //check input params and validate input
            
            $paging_limit_number = SystemConfigModel::model()->findByPk('1')->paging_limit_number;
            $pagevals['status'] = isset($_GET['status']) ? $_GET['status'] : 'active';
            $pagevals['search_string'] = isset($_GET['search_string']) ? $_GET['search_string'] : '';
            $pagevals['page_number'] = isset($_GET['page_number']) ? intval($_GET['page_number']) : 1;
            $pagevals['category_id'] = isset($_GET['category_id']) ? $_GET['category_id'] : 'all';
            $pagevals['hot_status'] = isset($_GET['hot_status']) ? $_GET['hot_status'] : 'all';
            $pagevals['color'] = isset($_GET['color']) ? $_GET['color'] : 'all';
            $pagevals['size'] = isset($_GET['size']) ? $_GET['size'] : 'all';
            $pagevals['brand'] = isset($_GET['brand']) ? $_GET['brand'] : 'all';

            $conditions = array();

            //validate input
            if($pagevals['page_number'] <= 0 || is_numeric($pagevals['page_number'])!= true )$pagevals['page_number']=1;
            if($pagevals['status'] != 'all'){ $conditions['status'] = $pagevals['status']; }

            if($pagevals['hot_status'] != 'all'){$conditions['hot_status'] = $pagevals['hot_status'];}
            if($pagevals['color'] != 'all'){$conditions['color'] = $pagevals['color'];}
            if($pagevals['size'] != 'all'){$conditions['size'] = $pagevals['size'];}
            if($pagevals['brand'] != 'all'){$conditions['brand'] = $pagevals['brand'];}
        

            $sort = array('create_time'=>'desc');
            if($pagevals['category_id'] != 'all'){
                $fields = array('category_id');
                $data = ProductModel::model()->SearchMultiField(';'.$pagevals['category_id'].';', $conditions, $pagevals['page_number'], $paging_limit_number, $fields);
                $pagevals['total_row'] = ProductModel::model()->countSearch(';'.$pagevals['category_id'].';', $conditions, $fields);
            }
            elseif($pagevals['search_string'] == null || $pagevals['search_string'] == ""){
                $data = ProductModel::model()->getByPage($conditions, $pagevals['page_number'], $paging_limit_number, $sort);
                $pagevals['total_row'] = ProductModel::model()->countRow($conditions);
            }else{
                $fields = array('name');
                $data = ProductModel::model()->SearchMultiField($pagevals['search_string'], $conditions, $pagevals['page_number'], $paging_limit_number, $fields);
                $pagevals['total_row'] = ProductModel::model()->countSearch($pagevals['search_string'], $conditions, $fields);
            }




            $filter_fields = array(
                'color'=>'asc',
                'size'=>'asc',
                'brand'=>'asc',
                'status'=>'asc',
            );

            //process and render data
            
            $pagevals['filter_label'] = $this->getFilterValue($filter_fields);


            $pagevals['total_page'] = ProductModel::model()->countPage($pagevals['total_row'], $paging_limit_number);
            $pagevals['row_start'] = ProductModel::model()->get_start_row($pagevals['total_row'], $pagevals['page_number'], $paging_limit_number);
            $pagevals['row_end'] = ProductModel::model()->get_end_row($pagevals['total_row'], $pagevals['page_number'], $paging_limit_number);
            $pagevals['status'] = $pagevals['status'];
            $pagevals['hot_status']= $pagevals['hot_status'];
            $pagevals['category_id']= $pagevals['category_id'];


            $this->display("product/index", array('data'=>$data, 'pagevals'=>$pagevals) );
        }



    public function build_category_tree(array $elements, $parentId = 0) {
        $branch = array();

        foreach ($elements as $element) {
            if ($element['parent_id'] == $parentId) {
                $children = $this->build_category_tree($elements, $element['id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }

        return $branch;
    }

    public function actionCreate()
	{
            if(isset($_POST['search_string'])){
                $search_sesult = ProductModel::model()->SearchMultiField($_POST['search_string'], array('status'=>'active'), 1, 30, array('name'),array('id','name'));
                if(count($search_sesult) != 0){
                    $result_string = '<table>';
                    
                    foreach($search_sesult as $product){
                        $result_string .= '
                                            <tr>
                                                <td><input type="checkbox" class="related_products" value="'.$product['id'].'"></td>
                                                <td><a href="'.$this->createUrl('product/view',array('id'=>$product['id'],'slug'=>$product['slug'])).'"><label>'.$product['name'].'</label></a></td>
                                            </tr>
                                            ';
                    }
                    $result_string .= '</table>';
                    echo $result_string;
                }else{
                    echo '<br /><label>Không tìm thấy kết quả nào</label><br />';
                }

            }else{

                $pagevals = array(
                    'page_title' => "Quản trị sản phẩm",
                    'subpage_title' => 'Tạo sản phẩm mới',
                    //'action' => 'product/abc'
                );


                //get category tree
                $category_tree = array();
                $categories = PrCategoryModel::model()->findAll('',array('id','name','parent_id'));
                $categories_arr = array();
                foreach($categories as $cate){
                    $categories_arr[] = $cate->attributes;
                }
                $pagevals['category_tree'] = $this->build_category_tree($categories_arr);

                $selection_fields = array(

                    'color'=>'asc',
                    'size'=>'asc',
                    'brand'=>'asc',
                    'material'=>'asc',
                    'weight'=>'asc',

                );

                //get category name
                $category_filter_laber = array();
                $categories = PrCategoryModel::model()->getAll();
                if(is_array($categories)){
                    foreach($categories as $value){
                        if($value != null){
                           $category_filter_laber[$value['id']]  = $value['name'];
                        }
                    }
                }
                $pagevals['selection_label'] = $this->getFilterValue($selection_fields);
                $pagevals['selection_label']['category'] = $category_filter_laber;

//                print_r('<pre>');
//                print_r($pagevals['selection_label']);
//                print_r('</pre>');
//                exit();

                ///--------------------------
                $time=time();
                $pagevals['time']=$time;
                $product = new ProductModel;
                if(isset($_POST['name'])){
                    if($_POST['slug'] ==  ''){
                        $_POST['slug'] = $this->convertToAlias($_POST['name']);
                    }
                    if($_POST['brand'] == ''){
                        $_POST['brand'] = $_POST['new_brand'];
                    }
                    if($_POST['color'] == ''){
                        $_POST['color'] = $_POST['new_color'];
                    }
                    if($_POST['size'] == ''){
                        $_POST['size'] = $_POST['new_size'];
                    }
                    if($_POST['material'] == ''){
                        $_POST['material'] = $_POST['new_material'];
                    }
                    if($_POST['new_weight'] != ''){
                        $_POST['weight'] = $_POST['new_weight'];
                    }
                    $product->attributes = array(
                                //'id' => 'ID',
                                'name' => $_POST['name'],
                                'slug' => $_POST['slug'],
                                'description' => $_POST['description'],
                                'size' => $_POST['size'],
                                'color' => $_POST['color'],
                                'material'=> $_POST['material'],
                                'weight' => $_POST['weight'],
                                'brand' => $_POST['brand'],
                                'number' => $_POST['number'],
                                'price' => $_POST['price'],
                                'price_sale_off' => $_POST['price_sale_off'],
                                'promotion' => $_POST['promotion'],
                                'category_id' => $_POST['category_id'],
                                'hot_status' => $_POST['hot_status'],
                                'status' => $_POST['status'],
                                'images' => $_POST['images'],
                                'thumb' => $_POST['thumb'],
                                'related_products' => $_POST['related_products'],
                                'tags' => $_POST['tags'],
                                'create_time' => $time,
                                'update_time' => $time,
                            );
                    if($product->save(false)){
                        $this->redirect(array('index','status'=>$_POST['status']));
                    }
                }
                $this->display("product/create", array('pagevals'=>$pagevals));
            }
	}


        public function actionEdit($id)
	{
            if(!isset($_GET['id'])){
                die('Post not found');
            }
            $pagevals = array(
                'page_title' => "Quản trị sản phẩm",
                'subpage_title' => 'Sửa sản phẩm',
                //'action' => 'product/abc'
            );

            //-------------------------------
            //get post data
            $product = ProductModel::model()->findByPk($id);
            if(!is_object($product)){
                die('Post not found');
            }

            //get category tree
            $category_tree = array();
            $categories = PrCategoryModel::model()->findAll('',array('id','name','parent_id'));
            $categories_arr = array();
            foreach($categories as $cate){
                $categories_arr[] = $cate->attributes;
            }
            $pagevals['category_tree'] = $this->build_category_tree($categories_arr);

            $selection_fields = array(

                'color'=>'asc',
                'size'=>'asc',
                'brand'=>'asc',
                'material'=>'asc',
                'weight'=>'asc',

            );


            $pagevals['selection_label'] = $this->getFilterValue($selection_fields);


            ///--------------------------
            $time=time();
            if(isset($_POST['name'])){
                if($_POST['slug'] ==  ''){
                    $_POST['slug'] = $this->convertToAlias($_POST['name']);
                }
                if($_POST['new_brand'] != ''){
                    $_POST['brand'] = $_POST['new_brand'];
                }
                if($_POST['new_color'] != ''){
                    $_POST['color'] = $_POST['new_color'];
                }
                if($_POST['new_size'] != ''){
                    $_POST['size'] = $_POST['new_size'];
                }
                if($_POST['new_material'] != ''){
                    $_POST['material'] = $_POST['new_material'];
                }
                if($_POST['new_weight'] != ''){
                    $_POST['weight'] = $_POST['new_weight'];
                }
                $product->attributes = array(
                    //'id' => 'ID',
                    'name' => $_POST['name'],
                    'slug' => $_POST['slug'],
                    'description' => $_POST['description'],
                    'size' => $_POST['size'],
                    'color' => $_POST['color'],
                    'material'=> $_POST['material'],
                    'weight' => $_POST['weight'],
                    'brand' => $_POST['brand'],
                    'number' => $_POST['number'],
                    'price' => $_POST['price'],
                    'price_sale_off' => $_POST['price_sale_off'],
                    'promotion' => $_POST['promotion'],
                    'category_id' => $_POST['category_id'],
                    'hot_status' => $_POST['hot_status'],
                    'status' => $_POST['status'],
                    'images' => $_POST['images'],
                    'thumb' => $_POST['thumb'],
                    'related_products' => $_POST['related_products'],
                    'tags' => $_POST['tags'],
                    //'create_time' => $time,
                    'update_time' => $time,
                );
                if($product->save(false)){
                    $this->redirect(array('product/index','status'=>$_POST['status']));
                }
            }
            
            
            
            $this->display("product/edit", array('pagevals'=>$pagevals,'data'=>$product->attributes));
        }

        
        public function doAcion($status,$data){
            $i = 0;
            $time = time();
            $game_id = explode(';', $data);
            if(sizeof($game_id) == 0){
                echo 0;
            }
            else{
                foreach($game_id as $value){
                    if($value != 0){
                        $result = ProductModel::model()->modify($value,array('status'=>$status,'update_time'=>$time));
                        if($result == true){
                            $i++;
                        }
                    }
                }
                echo $i;
            }
        }
        
        
        public function actionCopy(){
            if(isset($_POST['game_id'])){
                $i = 0;
                $game_id = explode(';', $_POST['game_id']);
                if(sizeof($game_id) == 0){
                    echo 0;
                }
                else{
                    foreach($game_id as $value){
                        if($value != 0){
                            $result = ProductModel::model()->copy($value);
                            if($result == true){
                                $i++;
                            }
                        }
                    }
                    echo $i;
                }
            }
        }
        
        public function actionRemove(){
            if(isset($_POST['remove_ids'])){
                $this->doAcion('deleted', $_POST['remove_ids']);
            }
            if(isset($_POST['id'])){
                $result = ProductModel::model()->modify($_POST['id'],array('status'=>'deleted','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionPending(){
            if(isset($_POST['pending_ids'])){
                $this->doAcion('pending', $_POST['pending_ids']);
            }
            if(isset($_POST['id'])){
                $result = ProductModel::model()->modify($_POST['id'],array('status'=>'pending','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionApprove(){
            if(isset($_POST['approve_ids'])){
                $this->doAcion('approved', $_POST['approve_ids']);
            }
            if(isset($_POST['id'])){
                $result = ProductModel::model()->modify($_POST['id'],array('status'=>'approved','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionActive(){
            if(isset($_POST['active_ids'])){
                $this->doAcion('active', $_POST['active_ids']);
            }
            if(isset($_POST['id'])){
                $result = ProductModel::model()->modify($_POST['id'],array('status'=>'active','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionBlock(){
            if(isset($_POST['block_ids'])){
                $this->doAcion('blocked', $_POST['block_ids']);
            }
            
            if(isset($_POST['id'])){
                $result = ProductModel::model()->modify($_POST['id'],array('status'=>'blocked','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function actionRestore(){
            if(isset($_POST['restore_ids'])){
                $this->doAcion('pending', $_POST['restore_ids']);
            }
            if(isset($_POST['id'])){
                $result = ProductModel::model()->modify($_POST['id'],array('status'=>'pending','update_time'=>time()));
                if($result == true) echo 'success';
            }
            
        }
        
        public function getFilterValue($fields){
            if(is_array($fields)){
                $result = array();
                foreach($fields as $key => $value){
                    $temp = ProductModel::model()->getUnique($key, $value);
                    if(is_array($temp)){
                        foreach($temp as $val){
                            if($val[$key] !=null && $val[$key]!=''){
                                $result[$key][]= $val[$key];
                            }
                        }
                    }
                }
                return $result;
            }else return null;
        }
}
